package com.hadwinling.blog.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hadwinling.blog.entity.Admin;
import com.hadwinling.blog.entity.Article;
import com.hadwinling.blog.entity.Tag;
import com.hadwinling.blog.service.ArticleService;
import com.hadwinling.blog.service.TagService;
import com.hadwinling.blog.util.Baiducensor;
import com.hadwinling.blog.util.FileUpload;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章控制器
 * @author HadwinLing
 * @version V1.0
 * @Package com.hadwinling.blog.controller
 * @date 2020/8/19 7:46
 */
@Controller
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private FileUpload fileUpload;
    @Autowired
    private TagService tagService;

    @Value("${admin.article.page.pageSize}")
    private int pageSize;
    @Value("${page.navigatePage}")
    private int navigatePage;

    /**
     * 进入管理员页面的查看文章
     * @param model
     * @param pageNum
     * @return
     */
    @GetMapping("/admin/article")
    public String article(Model model, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum){
        List<Tag> tagList = tagService.selectAllByState(1);
        //分页
        PageHelper.startPage(pageNum,pageSize);
        List<Article> articleList = articleService.selectAllByStateOrderByCreatetimeDesc(1);
        PageInfo<Article> pageInfo = new PageInfo<>(articleList,navigatePage);
        //统计多少条数据
        int total = articleService.countByState(1);
        model.addAttribute("total",total);
        //当前页码
        int currPage = pageInfo.getPageNum();
        //总页数
        int totalPage = pageInfo.getPages();
        //所有页面
        int [] pages = pageInfo.getNavigatepageNums();
        //保存分页信息
        model.addAttribute("currPage",currPage);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("pages",pages);
        model.addAttribute("articleList",articleList);
        model.addAttribute("tagList",tagList);
        model.addAttribute("tagid",-1);
        return "AdminCenter/article";
    }

    /**
     * 查找文章
     * @param article
     * @param model
     * @param request
     * @param pageNum
     * @return
     */
    @PostMapping("/admin/article")
    public String selectArticleByTitleOrTag(Article article,Model model, HttpServletRequest request,
                                            @RequestParam(value = "pageNum",defaultValue = "1") int pageNum){
        //获取前台下拉框的值
        String artTypeIdValue = request.getParameter("tagid");
//        System.out.println("artTypeIdValue"+artTypeIdValue);
        if (artTypeIdValue!=null){
            //设置文章类别id
            article.setTagid(Integer.parseInt(artTypeIdValue));
        }
        //设置文章的状态
        article.setState(1);
        List<Tag> tagList = tagService.selectAllByState(1);
        //分页
        PageHelper.startPage(pageNum,pageSize);
        List<Article> articleList = articleService.selectAllSelective(article);
        PageInfo<Article> pageInfo = new PageInfo<>(articleList,navigatePage);

        //统计多少条数据
        int total = articleList.size();
        model.addAttribute("total",total);

        //当前页码
        int currPage = pageInfo.getPageNum();
        //总页数
        int totalPage = pageInfo.getPages();
        //所有页面
        int [] pages = pageInfo.getNavigatepageNums();
        //保存分页信息
        model.addAttribute("currPage",currPage);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("pages",pages);
        model.addAttribute("articleList",articleList);
        model.addAttribute("tagList",tagList);
//        System.out.println("article:"+article);
        model.addAttribute("tagid",article.getTagid());
//        System.out.println("tagid:"+article.getTagid());
        return "AdminCenter/article";
    }


    /**
     *
     * 跳转到发布文章页面
     * @param model
     * @return
     */
    @GetMapping("/admin/addArticle")
    public String toAddArticlePage(Model model){
        List<Tag> tagList = tagService.selectAllByState(1);
        model.addAttribute("tagList",tagList);
        return "AdminCenter/articleAdd";
    }

    /**
     * 执行发布操作
     * @param imgFileUp
     * @param article
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/admin/addArticle")
    public String addArticle(MultipartFile imgFileUp, Article article,
                             HttpServletRequest request, HttpServletResponse response ) throws IOException {
        Admin admin = (Admin) request.getSession().getAttribute("currAdmin");
        int adminId = admin.getId();
        //获取前台下拉框的值
        String artTypeId = request.getParameter("artTypeId");
        //设置文章类别id
        int tagId = Integer.parseInt(artTypeId);
        article.setTagid(tagId);
        //获取前台的富文本的内容
        String content = request.getParameter("mytxtIntro");
        //设置文章的内容
        article.setContent(content);
        //设置发布时间
        article.setCreatetime(new Date());
        //保存封面
        String imgUrl = fileUpload.FileUploadToQiNiu(imgFileUp);
        article.setPhoto(imgUrl);
        //设置文章的状态
        article.setState(1);
        //设置为管理者发布的
        article.setAdminid(adminId);
        //设置浏览量和点赞量
        article.setLikecount(0);
        article.setVisitcount(0);
        //设置置顶
        article.setTop(0);
        //使用百度检测
        JSONObject jsonObject= new JSONObject();
        org.json.JSONObject textcensorresult= Baiducensor.textCheck(content);
        org.json.JSONObject imgcensorresult=Baiducensor.imgCheck(imgUrl);
        if ((textcensorresult.get("conclusion").equals("合规"))&&(imgcensorresult.get("conclusion").equals("合规"))){
            articleService.insertSelective(article);
            //每成功发布一篇文章，将tag对应的文章数量进行增加
            tagService.updateTagnumById(1,tagId);
            return "redirect:/admin/article";
        }
//        PrintWriter out=response.getWriter();
//        out.print("<script>alert('您输入的内容或图片中包含不合规的信息，请修改！');</script>");
        return "redirect:/admin/addArticle?rslt=1";
    }

    /**
     * 处理富文本编辑器中图片的上传
     * @param imgs
     * @return
     */
    @PostMapping("/admin/article/uploadimg")
    @ResponseBody
    public Map<String, String> uploadImgToQiNiu(MultipartFile imgs){
//        System.out.println("开始上传");
        // 上传的用户
        // 上传到七牛云返回的连接
        String imgurl = null;
        try {
            imgurl = FileUpload.FileUploadToQiNiu(imgs);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 输出返回的链接
//        System.out.println(imgurl);

        Map<String, String> map = new HashMap();
        map.put("url", imgurl);
        return map;
    }

    /**
     *
     * 执行删除标签操作
     * @param articleid
     * @return
     */
    @PostMapping("/admin/deleteArticle")
    @ResponseBody
    public String deleteArticle(@RequestParam(name = "articleid") int articleid){
        Article article = articleService.selectByPrimaryKey(articleid);
        article.setState(0);
        articleService.updateByPrimaryKeySelective(article);
        return "1";
    }

    /**
     * 执行取消置顶操作
     * @param articleid
     * @return
     */
    @PostMapping("/admin/noArticleTop")
    @ResponseBody
    public String noArticleTop(@RequestParam(name = "articleid") int articleid){
        List<Article> topArticleList = articleService.selectAllByStateAndTop(1,1);
        if (topArticleList.size()<=4){
            //无法取消置顶操作
            return "0";
        }
        //执行取消置顶操作
        articleService.updateTopById(0,articleid);
        return "1";
    }

    /**
     * 执行置顶操作
     * @param articleid
     * @return
     */
    @PostMapping("/admin/addArticleTop")
    @ResponseBody
    public String addArticleTop(@RequestParam(name = "articleid") int articleid){
        List<Article> topArticleList = articleService.selectAllByStateAndTop(1,1);
        if (topArticleList.size()>4){
            //无法置顶操作
            return "0";
        }
        //执行置顶操作
        articleService.updateTopById(1,articleid);
        return "1";
    }

    /**
     * 跳转到修改页面
     * @param articleid
     * @return
     */
    @GetMapping("/admin/updateArticle/{articleid}")
    public String updateArticle(@PathVariable(name = "articleid") int articleid,Model model){
        Article article = articleService.selectByPrimaryKey(articleid);
        model.addAttribute("article",article);
        return "AdminCenter/articleUpdate";
    }





}
